import json
import os
from datetime import datetime

class FileHandler:
    @staticmethod
    def save_data(data, filename):
        # 获取当前日期并格式化为字符串
        date_string = datetime.now().strftime("%Y%m%d")
        
        # 在文件名中加入日期时间戳
        timestamped_filename = f"{date_string}_{filename}"
        
        # 确保/data文件夹存在
        os.makedirs('data', exist_ok=True)
        
        # 从filename中取出部分作为文件夹名
        folder_name = filename.split("_")[0]
        
        # 在/data文件夹下创建文件夹
        os.makedirs(os.path.join('data', folder_name), exist_ok=True)
        
        # 将文件保存到对应文件夹下
        with open(os.path.join('data', folder_name, timestamped_filename), "w", encoding="utf-8") as file:
            json.dump(data, file, ensure_ascii=False, indent=4)
    @staticmethod
    def save_data_without_folder_name(data, filename):
         # 获取当前日期并格式化为字符串
        date_string = datetime.now().strftime("%Y%m%d")
        
        # 在文件名中加入日期时间戳
        timestamped_filename = f"{date_string}_{filename}"
        
        # 确保/data文件夹存在
        os.makedirs('data', exist_ok=True)
        
        
        # 在/data文件夹下创建文件夹
        os.makedirs(os.path.join('data', 'OneBszn_data.txt'), exist_ok=True)
        
        # 将文件保存到对应文件夹下
        with open(os.path.join('data', 'OneBszn_data.txt', timestamped_filename), "w", encoding="utf-8") as file:
              file.write(str(data))

    @staticmethod
    def append_update_log(update_log_file, date_str, differences):
        with open(update_log_file, 'a') as f:
            f.write(f"更新日期: {date_str}\n")
            f.write("======================================\n")
            for diff in differences:
                f.write(f"编号: {diff[0]}, 字段: {diff[1]}, 旧值: {diff[2]}, 新值: {diff[3]}\n")
            f.write("\n")
